<?php
/**
 * Created by PhpStorm.
 * User: fengyan
 * Date: 17-11-3
 * Time: 下午2:16
 */

namespace App\Repositories\Portal;


use App\Exceptions\MyException;
use App\Models;

class DocumentRepository extends PortalRepository
{

    public function __construct()
    {
        parent::__construct();
        $this->model = new Models\Portal\Document();
    }


    protected static $modelList = [
        'news' => '\\App\\Models\\Portal\\DocumentNews',
        'photo' => '\\App\\Models\\Portal\\DocumentPhoto',
        'page' => '\\App\\Models\\Portal\\DocumentPage',
    ];

    private static $instance;

    /**
     * 实现单例
     */
    public static function getInstance()
    {
        if (!(self::$instance instanceof self)) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * 声明实例模型
     * @param array $filter
     * @return mixed
     */
    public function getSelectModel(array $filter = []) : \Illuminate\Database\Eloquent\Builder
    {
        $model = $this->model;

        //  站点编号
        $model = $this->getSiteIdModel($model, $filter);

        //  分类编号
        if (isset($filter['category_id']) && !empty($filter['category_id'])) {
            if (is_array($filter['category_id'])) {
                $model = $model->whereIn('category_id', $filter['category_id']);
            } else {
                $model = $model->where('category_id', '=', $filter['category_id']);
            }
        }

        //  文档类型
        if (isset($filter['document_type'])) {
            $filter['document_type'] = is_array($filter['document_type']) ? $filter['document_type'] : explode(',', $filter['document_type']);
            $model = $model->whereIn('document_type', (array)$filter['document_type']);
        }

        //  创建用户编号
        if (isset($filter['create_uid']) && !empty($filter['create_uid'])) {
            $model = $model->where('create_uid', '=', (int) $filter['create_uid']);
        }

        //  ip地址
        if (isset($filter['ip2long']) && !empty($filter['ip2long'])) {
            $model = $model->where('ip2long', '=', $filter['ip2long']);
        }

        //  是否需要审核
        if (isset($filter['is_audit'])) {
            $model = $model->where('is_audit', '=', $filter['is_audit']);
        }

        //  状态
        if (isset($filter['status'])) {
            $model = $model->where('status', '=', $filter['status']);
        }

        //  关键词
        if (isset($filter['keywords'])) {
            $model = $model->where('title', 'like', '%'.$filter['keywords'].'%')->orWhere('description', 'like', '%'.$filter['keywords'].'%');
        }

        $model = $model->where('deleted_at', null);

        return $model;
    }

    /**
     * 获取后台分页
     * @param null $documentType
     * @param null $categoryId
     * @param null $keywords
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getAdminPaginateData($documentType = null, $categoryId = null, $keywords = null) : \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return $this->getSelectModel([
            'document_type' => $documentType,
            'category_id' => $categoryId,
            'keywords' => $keywords
        ])->orderBy('id', 'desc')->paginate($this->pageSize);
    }

    /**
     *
     * @param array $document
     * @param array $extend
     * @param $type
     * @param string $action
     * @return Models\Portal\Document
     * @throws MyException
     */
    public function saveData(array $document, array $extend, $type, $action = 'add')
    {
        $document['document_type'] = $type;

        if (empty(get_value($document, 'title', ''))) {
            throw new MyException("标题不能为空");
        }

        if (empty(get_value($document, 'category_id', ''))) {
            throw new MyException("栏目不能为空");
        }

        if (array_key_exists('is_audit', $document)) {
            if ($document['is_audit'] == 0) {
                $document['status'] = 99;
            } else {
                $document['status'] = $document['is_audit'];
            }
        }

        switch ($type) {
            case 'photo':
                $extend['pic_text'] = json_encode(array_values(get_value($extend, 'pic_text', [])));
                break;
            case 'page':
                $extend['pic_text'] = json_encode(array_values(get_value($extend, 'pic_text', [])));
                break;
        }

        $model = $this->model;
        if ($action == 'edit') {
            $model = $model->find(get_value($document, $this->getPrimaryKey(), 0));
            if (empty($model)) {
                $model = $this->model;
            }

            foreach ($document as $key=>$value) {
                if (empty($value) && $key == $this->getPrimaryKey()) {
                    continue;
                }

                $model->$key = $value;
            }

            if (!$model->save($document)) {
                throw new MyException("更新基础数据失败");
            }
        } else {
            foreach ($document as $key=>$value) {
                if (empty($value) && $key == $this->getPrimaryKey()) {
                    continue;
                }

                $model->$key = $value;
            }

            if (!$model->save()) {
                throw new MyException("添加基础数据失败");
            }
        }

        $extend['id'] = $model->id;

        if (isset($extend['template_detail']) && !empty($extend['template_detail'])) {
            $extend['template_detail'] = $extend['template_detail'].$type;
        }

        if (empty($model->{$type}) || !($model->{$type} instanceof self::$modelList[$type])) {
            $model->{$type} = new self::$modelList[$type]();
        }

        foreach ($extend as $key=>$value) {
            $model->{$type}->{$key} = $value;
        }

        $re = $model->{$type}->save();

        if (!$re) {
            throw new MyException("更新扩展数据失败");
        }

        return $model;
    }


    /**
     * 根据栏目编号获取对应的单文章信息
     * @param int $categoryId
     * @param int $status
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    public function getPageByCategoryId(int $categoryId, int $status = 99)
    {
        return $this->getSelectModel([
            'category_id' => $categoryId,
            'status' => $status
        ])->first();
    }

    /**
     * 更新文档状态
     * @param $ids
     * @param int $status
     */
    public function setStatus($ids, $status = 0)
    {
        if (is_array($ids)) {
            return $this->model->whereIn('id', $ids)->update([
                'status' => $status
            ]);
        }

        return $this->model->where('id', '=', $ids)->update([
            'status' => $status
        ]);
    }
}